import pandas as pd

def kdj(df, n=9, m1=3, m2=3):
    low_list = df['low'].rolling(n).min()
    low_list.fillna(value=df['low'].expanding().min(), inplace=True)
    high_list = df['high'].rolling(n).max()
    high_list.fillna(value=df['high'].expanding().max(), inplace=True)
    rsv = (df['close'] - low_list) / (high_list - low_list) * 100
    k = rsv.ewm(com=m1-1, adjust=False).mean()
    d = k.ewm(com=m2-1, adjust=False).mean()
    j = 3 * k - 2 * d
    return pd.DataFrame({'k': k, 'd': d, 'j': j})

def kdj_cross(dataframe, n=9, m1=3, m2=3, threshold_low=False, threshold_high=False):
    df = kdj(dataframe, n, m1, m2)
    list_cross = []
    for index in range(len(dataframe)):
        if index == 0:
            continue
        current_gold = df['k'].iloc[index] > df['d'].iloc[index] and df['k'].iloc[index-1] < df['d'].iloc[index-1]
        current_dead = df['k'].iloc[index] < df['d'].iloc[index] and df['k'].iloc[index-1] > df['d'].iloc[index-1]
        if threshold_low is not False and threshold_high is not False:
            if current_gold and df['d'].iloc[index] < threshold_low:
                list_cross.append((index, 'gold'))
            elif current_dead and df['d'].iloc[index] > threshold_high:
                list_cross.append((index, 'dead'))
            else:
                pass
        else:
            if current_gold:
                list_cross.append((index, 'gold'))
            elif current_dead:
                list_cross.append((index, 'dead'))
            else:
                pass
    return list_cross